
export default () => {


  /**
   * 获取最小定时间隔，进行使用，节省资源
   */
  window.customerTaskWorkTimeLen = 2000;
  function getMinCustomerTaskWorkTimeLen() {
    const timeLen = loopTaskList.map(item => item.interval);
    return window.customerTaskWorkTimeLen = Math.min(...timeLen);
  }

  /**
   * method:function, //执行函数
   * immediate:boolean, //是否立即执行
   * interval:number //定时间隔
   */
  let loopTaskList = [];
  window.customerWorkTaskIntervalId = null;
  /**
   * 创建Task任务
   */
  window._createdLoopTask = window._createdLoopTask || function () {
    console.log(window.customerTaskWorkTimeLen);
    let count = 0;
    clearInterval(window.customerWorkTaskIntervalId);
    window.customerWorkTaskIntervalId = setInterval(() => {
      loopTaskList.map(item => {
        const times = Math.ceil(item.interval / window.customerTaskWorkTimeLen);
        const immediate = item.immediate;
        if (immediate || (count % times == 0 && count > 0)) {
          try {
            if (typeof item.method == 'function') {
              item.method();
            }
          } catch (error) {
            console.error(error);
          }
          item.immediate = false;
        }
      })
      count++;
    }, window.customerTaskWorkTimeLen);
  }
  /**
   * 添加定时任务到列表
   * @param {Object} _loopTaskList 
   */
  window.pushLoopTask = window.pushLoopTask || function (_loopTask) {
    loopTaskList.push(_loopTask);
    getMinCustomerTaskWorkTimeLen();
  }
  /**
    * 添加定时任务到列表
    * @param {Array} _loopTaskList 
    */
  window.pushLoopTaskList = window.pushLoopTaskList || function (_loopTaskList) {
    loopTaskList = loopTaskList.concat(_loopTaskList);
    getMinCustomerTaskWorkTimeLen();
  }

  /**
   * 执行定时任务
   * @returns 
   */
  window.executeLoopTask = window.executeLoopTask || function (isStart = false) {
    clearInterval(window.customerWorkTaskIntervalId);
    if (!isStart) {
      return;
    }
    getMinCustomerTaskWorkTimeLen();
    _createdLoopTask();
  }

  window.clearTask = window.clearTask || function () {
    clearInterval(window.customerWorkTaskIntervalId);
    loopTaskList = [];
  }

  return {
    pushLoopTask: window.pushLoopTask,
    pushLoopTaskList: window.pushLoopTaskList,
    executeLoopTask: window.executeLoopTask,
    clearTask: window.clearTask,
  }
}
